package com.wanxin.car.util.helper;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.util.StringUtils;

/**
 * spring mvc date parser
 * can parse date format yyyy-MM-dd or yyyy-MM-dd HH:mm:ss
 * null and empty string parse to null
 * @author lqk
 */
public class MyDateEditor extends CustomDateEditor{
	
	private SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
	private SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	/**
	 * param use null 
	 */
	public MyDateEditor(DateFormat dateFormat, boolean allowEmpty) {
		super(dateFormat, allowEmpty);
	}
	
	/**
	 * Parse the Date from the given text, using the specified DateFormat.
	 */
	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		
		if( !StringUtils.hasText(text) ){
			setValue(null);
			return;
		}
		
		try{
			if( text.length()==10 ){
				setValue( sdf1.parse(text));
			} else if(text.length()==19 ){
				setValue( sdf2.parse(text));
			} else {
				throw new IllegalArgumentException("unkown date str format,date str is:" + text);
			}
		} catch (ParseException e){
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		
		
	}

	/**
	 * Format the Date as String, using the specified DateFormat.
	 */
	@Override
	public String getAsText() {
		Date value = (Date) getValue();
		return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(value);
	}

}
